package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security 配置类
 */
//@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 注销登录配置
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").permitAll();
        // 设置自定义登录页面
        http.formLogin()
                .loginPage("/login.html") // 自定义登录页面
                .loginProcessingUrl("/login") // 登录请求地址（系统默认，无需创建）[自定义页面此项必须设置]
                .defaultSuccessUrl("/home.html").permitAll(); // 登录成功页面
        http.csrf().disable(); // 关闭 csrf 验证
//        // 自定义从数据库查询用户信息
//        http.userDetailsService(userDetailsService);
        // 请求访问策略
        http.authorizeRequests()
                .antMatchers("/login.html",
                        "/login").permitAll() //放行资源，自定义添加
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/user/**").hasAnyAuthority("admin", "user")
                .anyRequest().authenticated(); //除以上放行资源外，其他全部拦截
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    public InMemoryUserDetailsManager userDetailsService() {
//        // 设置用户名、密码和权限
//        UserDetails user = User.builder()
//                .username("user")
//                .password(passwordEncoder().encode("123456"))
//                .roles("admin")
//                .build();
//        return new InMemoryUserDetailsManager(user);
//    }
}
